'use strict';

const Controller = require('egg').Controller;

class ChatController extends Controller {
  async connect() {
    const { ctx, app } = this;
    if (!ctx.websocket) {
      ctx.throw(400, "非法访问");
    }

    // console.log(`clients: ${app.ws.clients.size}`);

    // 监听接收消息和关闭socket
    ctx.websocket
      .on("message", (msg) => {
        // console.log('接收消息', msg);
      })
      .on("close", (code, reason) => {
        // 用户下线
        console.log("用户下线", code, reason);
        let user_id = ctx.websocket.user_id;
        if (app.ws.user && app.ws.user[user_id]) {
          delete app.ws.user[user_id];
        }
      });
  }
  async send() {
    const currentuserid = this.ctx.authUser.id;
    console.log(this.ctx.request.body,"this.ctx.request.body")
    this.ctx.validate({
      to_id: {
        type: "int", required: true, desc: "接收人/群id"
      },
      chat_type: {
        type: "string",
        range: {
          in: ['user', 'group']
        },
        required: true,
        desc: "接收类型"
      },
      type: {
        type: "string",
        range: {
          in: ['text', 'image', 'video', 'audio','emoticon']
        },
        required: true,
        desc: "消息类型"
      },
      data: {
        type: "string",
        required: true,
        desc: "内容"
      },
      options: {
        type: "string",
        required: true,
        desc: "options"
      },
    });
    //单人聊天
    if (this.ctx.request.body.chat_type == 'user') {
      //验证你在对方好友是否存在，并且没有被拉黑
      const res = await this.app.model.Friend.findOne({
        where: {
          user_id: this.ctx.request.body.to_id,
          friend_id: currentuserid,
          isblack: 0
        },
        include: [{
          model: this.app.model.User,
          as: "userInfo"
        }, {
          model: this.app.model.User,
          as: "friendInfo"
        }]
      })

      if (!res) {
        return this.ctx.apiFail("对方不存在或者已拉黑")
      }
      if (res.userInfo.status !== 1) {
        return this.ctx.apiFail("该用户已被禁用")

      }
      let from_name = res.friendInfo.nickname ? res.friendInfo.nickname : res.friendInfo.username;
      if (res.nickname) {
        from_name = res.nickname

      }
      let message = {
        id: (new Date()).getTime(), // 唯一id，后端生成唯一id
        from_avatar: res.friendInfo.avatar,// 发送者头像
        from_name, // 发送者昵称
        from_id: currentuserid, // 发送者id
        to_id: this.ctx.request.body.to_id, // 接收人/群 id
        to_name: res.userInfo.nickname ? res.userInfo.nickname : res.userInfo.username, // 接收人/群 名称
        to_avatar: res.userInfo.avatar, // 接收人/群 头像
        chat_type: 'user', // 接收类型
        type: this.ctx.request.body.type,// 消息类型
        data: this.ctx.request.body.data, // 消息内容
        options: {}, // 其他参数
        create_time: (new Date()).getTime(), // 创建时间
        isremove: 0, // 是否撤回
      }
      if(message.type == 'video'){
        message.options.poster=message.data+'?x-oss-process=video/snapshot,t_10,m_fast,w_300,f_png'
      }

      //拿到对方的socket
      let socket = null;
      if (this.app.ws.user) {
        socket = this.app.ws.user[this.ctx.request.body.to_id];

      }
      //验证对方是否在线

      if (!socket) {
        console.log(123333, "343331")
        this.service.cache.setList("getmessage_" + this.ctx.request.body.to_id, message)

      } else {
        console.log(123333, "34333")
        //消息推送
        socket.send(JSON.stringify({
          msg: "ok",
          data: message
        }))
        //存到历史记录
        this.service.cache.setList(`chatlog_${this.ctx.request.body.to_id}_user_${currentuserid}`, message);


      }
      //存储到自己的聊天记录
      this.service.cache.setList(`chatlog_${currentuserid}_user_${this.ctx.request.body.to_id}`, message);
      //返回成功
      return this.ctx.apiSuccess(message);
    } else {
      console.log(this.ctx.request.body,"this.ctx.request.body")
      let group = await this.app.model.Group.findOne({
        where: {
          status: 1,
          id: this.ctx.request.body.to_id
        },
        include: [{
          model: this.app.model.GroupUser,
          attributes: ['user_id', 'nickname']
        }]
      })
      if (!group) {
        this.ctx.apiFail("该群聊不存在")
      }
      console.log(group, "group")
      let index = group.group_users.findIndex(item => item.user_id == currentuserid);
      if (index == -1) {
        this.ctx.apiFail("你已被移除群聊")
      }
      let message = {
        id: (new Date()).getTime(), // 唯一id，后端生成唯一id
        from_avatar: this.ctx.authUser.avatar,// 发送者头像
        from_name: group.group_users[index].nickname || this.ctx.authUser.nickname || this.ctx.authUser.username, // 发送者昵称
        from_id: currentuserid, // 发送者id
        to_id: this.ctx.request.body.to_id, // 接收人/群 id
        to_name: group.name, // 接收人/群 名称
        to_avatar: group.avatar, // 接收人/群 头像
        chat_type: 'group', // 接收类型
        type: this.ctx.request.body.type,// 消息类型
        data: this.ctx.request.body.data, // 消息内容
        options:{}, // 其他参数
        create_time: (new Date()).getTime(), // 创建时间
        isremove: 0, // 是否撤回
        group: group
      }
      if(message.type == 'video'){
        // "http://wangshuo-web1.oss-cn-beijing.aliyuncs.com/egg-oss-demo/77b6ol9tjrs0000.mp4?x-oss-process=video/snapshot,t_10,m_fast,w_300,f_png"
        message.options.poster=message.data+'?x-oss-process=video/snapshot,t_10,m_fast,w_300,f_png'
      }
      if(message.type == 'audio'){
        console.log((this.ctx.request.body.options),"JSON.parse(this.ctx.request.body.options)")
        message.options.time=(JSON.parse(this.ctx.request.body.options)).time
      }

      group.group_users.forEach(el => {
        if (el.user_id !== currentuserid) {
          //拿到对方的socket
          let socket = null;
          if (this.app.ws.user) {
            socket = this.app.ws.user[el.user_id];

          }
          //验证对方是否在线

          if (!socket) {
            console.log(123333, "343331")
            this.service.cache.setList("getmessage_" + el.user_id, message)

          } else {
            console.log(123333, "34333")
            //消息推送
            socket.send(JSON.stringify({
              msg: "ok",
              data: message
            }))
            //存到历史记录
            this.service.cache.setList(`chatlog_${el.user_id}_group_${currentuserid}`, message);
          }
        }
      });
      this.ctx.apiSuccess(message)


    }




  }
  //获取离线消息
  async getlxmessage() {
    // const { ctx, app, service } = this;
    // let current_user_id = ctx.authUser.id;
    // let key = 'getmessage_' + current_user_id;
    // let list = await service.cache.getList(key);
    // // 清除离线消息
    // await service.cache.remove(key);
    // // 批量推送
    // list.forEach(async (message) => {
    //     let d = JSON.parse(message);
    //     console.log(d,"d")
    //     ctx.sendAndSaveMessage(current_user_id, d.message, d.msg);
    // });
    // console.log(list,"list")
    // ctx.apiSuccess(list,"200")
    
    const currentuserid = this.ctx.authUser.id;
    let key = "getmessage_" + currentuserid
    let list=await this.service.cache.getList(key);
    //清除离线消息
    await this.service.cache.remove(key)
    //批量推送
    list.forEach(async(item)=>{
      let d=JSON.parse(item);
      console.log(d,"ddd")
      let socket = null;
      if (this.app.ws.user&& this.app.ws.user[currentuserid]) {
        socket = this.app.ws.user[currentuserid];

      }
      //验证对方是否在线

      if (!socket) {
        console.log(123333, "343331")
        this.service.cache.setList("getmessage_" + currentuserid, d)

      } else {
        console.log(123333, "34333")
        //消息推送
        socket.send(JSON.stringify({
          msg: "ok",
          data: d
        }))
        //存到历史记录
        this.service.cache.setList(`chatlog_${currentuserid}_user_${currentuserid}`, d);
      }
      // this.ctx.sendAndSaveMessage(currentuserid,d)
    })
    this.ctx.apiSuccess(list)
  }
}

module.exports = ChatController;
